<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="CAS" prop="casCode">
        <el-input
          v-model="queryParams.casCode"
          placeholder="请输入CAS"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['pms:product:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['pms:product:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pms:product:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['pms:product:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品ID" align="center" prop="productId" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="CAS" align="center" prop="casCode" />
      <el-table-column label="关联公司列表" align="center" width="200">
        <template slot-scope="scope">
          <template v-if="scope.row.companyList && scope.row.companyList.length">
            <div v-for="(company, index) in scope.row.companyList" :key="index">
              {{ index+1 }} - {{ company.companyName }}
            </div>
          </template>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="生产企业列表" align="center" width="200">
        <template slot-scope="scope">
          <template v-if="scope.row.companyRelate && scope.row.companyRelate.length">
            <div v-for="(company, index) in scope.row.companyRelate" :key="index">
              {{ index+1 }} - {{ company.companyName }}
            </div>
          </template>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="简介" align="center" prop="briefIntro" />
      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pms:product:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pms:product:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="行业">
          <el-checkbox v-model="industryExpand" @change="handleCheckedTreeExpand($event, 'industry')">展开/折叠</el-checkbox>
          <el-checkbox v-model="industryNodeAll" @change="handleCheckedTreeNodeAll($event, 'industry')">全选/全不选</el-checkbox>
          <el-checkbox v-model="form.industryCheckStrictly" @change="handleCheckedTreeConnect($event, 'industry')">父子联动</el-checkbox>
          <el-tree
            class="tree-border"
            :data="industryOptions"
            show-checkbox
            ref="industry"
            node-key="id"
            :check-strictly="!form.industryCheckStrictly"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="CAS" prop="casCode">
          <el-input v-model="form.casCode" placeholder="请输入CAS" />
        </el-form-item>
        <el-form-item label="上游产品">
         <el-select
          v-model="form.upstreamIds"
          style="width: 300px"
          multiple
          filterable
          remote
          reserve-keyword
          placeholder="请输入产品名称"
          :remote-method="getUpstreamProductList"
          :loading="initUpstreamProductsLoading">
          <el-option
            v-for="item in upstreamProductOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
         </el-select>
        </el-form-item>
        <el-form-item label="下游产品">
         <el-select
          v-model="form.downstreamIds"
          style="width: 300px"
          multiple
          filterable
          remote
          reserve-keyword
          placeholder="请输入产品名称"
          :remote-method="getDownstreamProductList"
          :loading="initDownstreamProductsLoading">
          <el-option
            v-for="item in downstreamProductOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
         </el-select>
        </el-form-item>
        <el-form-item label="简介" prop="briefIntro">
          <el-input v-model="form.briefIntro" type="textarea" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item label="生产企业">
         <el-select
          v-model="form.companyIds"
          style="width: 300px"
          multiple
          filterable
          remote
          reserve-keyword
          placeholder="请输入公司名称"
          :remote-method="getCompanyList"
          :loading="initCompanyListLoading">
          <el-option
            v-for="item in companyOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
         </el-select>
        </el-form-item>

        <el-form-item label="标签">
          <el-tag
            :key="tag"
            v-for="tag in dynamicTags"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)">
            {{tag}}
          </el-tag>
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          >
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>

<script>
import { listProduct, getProduct, delProduct, addProduct, updateProduct, changeProductStatus, productChain, companyListByProductId } from "@/api/pms/product";
import { treeselect as industryTreeselect, productIndustryTreeselect } from "@/api/pms/industry"
import { listCompany, listCompanyByProductId } from "@/api/pms/company"

export default {
  name: "Product",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品表格数据
      productList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      upstreamProductOptions: [],
      upstreamIds: [],
      initUpstreamProductsLoading: false,
      downstreamProductOptions: [],
      downstreamIds: [],
      initDownstreamProductsLoading: false,
      industryExpand: false,
      industryNodeAll: false,
      industryOptions: [],
      initCompanyListLoading: false,
      companyOptions: [],
      companyIds: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        casCode: null,
        briefIntro: null,
        status: undefined
      },
      // 表单参数
      form: {
        tags: []
      },
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" }
        ]
      },
      dynamicTags: [],
      inputVisible: false,
      inputValue: ''
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询产品列表 */
    getList() {
      this.loading = true;
      listProduct(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 查询行业树结构 */
    getIndustryTreeselect() {
      industryTreeselect().then(response => {
        this.industryOptions = response.data;
      });
    },
    // 所有行业节点数据
    getIndustryAllCheckedKeys() {
      // 目前被选中的行业节点
      let checkedKeys = this.$refs.industry.getCheckedKeys();
      // 半选中的行业节点
      let halfCheckedKeys = this.$refs.industry.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    
    /** 根据产品ID查询行业树结构 */
    getProductIndustryTreeselect(productId) {
      return productIndustryTreeselect(productId).then(response => {
        this.industryOptions = response.industries;
        return response;
      });
    },

    /**** 查询产品列表 */
    getUpstreamProductList(query) {
      if (query !== '') {
        let params = { productName: query }
        listProduct(params).then(response => {
          this.upstreamProductOptions = response.rows.map(item => {
                return {
                  value: item.productId,
                  label: item.productName
                };
               });
              this.initUpstreamProductsLoading = false;
        })
      }
    },

    getDownstreamProductList(query) {
      if (query !== '') {
        let params = { productName: query }
        listProduct(params).then(response => {
          this.downstreamProductOptions = response.rows.map(item => {
                return {
                  value: item.productId,
                  label: item.productName
                };
               });
              this.initDownstreamProductsLoading = false;
        })
      }
    },

    getCompanyList(query) {
      if (query !== '') {
        let params = { companyName: query }
        listCompany(params).then(response => {
          this.companyOptions = response.rows.map(item => {
                return {
                  value: item.companyId,
                  label: item.companyName
                };
               });
              this.initCompanyListLoading = false;
        })
      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.industry != undefined) {
        this.$refs.industry.setCheckedKeys([]);
      }
      this.industryExpand = false,
      this.industryNodeAll = false,
      this.upstreamProductOptions = [],
      this.downstreamProductOptions = [],
      this.companyOptions = [],
      this.dynamicTags = [],
      this.form = {
        productId: null,
        industryIds: [],
        industryCheckStrictly: true,
        productName: null,
        casCode: null,
        briefIntro: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        upstreamIds: [],
        downstreamIds: [],
        tags: []
      };
      this.resetForm("form");
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.productId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },

    // 行业（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'industry') {
        let treeList = this.industryOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.industry.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 行业（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'industry') {
        this.$refs.industry.setCheckedNodes(value ? this.industryOptions: []);
      }
    },
    // 行业（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'industry') {
        this.form.industryCheckStrictly = value ? true: false;
      }
    },
    /** 根据产品ID查询产业链 */
    getProductChain(productId, type) {
      return productChain(productId, type).then(response => {
        if (type === 'upstream') {
          this.upstreamProductOptions = response.products.map(item => {
              return {
                value: item.productId,
                label: item.productName
              };
            });
          this.form.upstreamIds = response.productIds;
        }else if (type === 'downstream') {
          this.downstreamProductOptions = response.products.map(item => {
              return {
                value: item.productId,
                label: item.productName
              };
            });
          this.form.downstreamIds = response.productIds;
        }
      })
    },

    /** 根据产品Id获取生产企业列表 */
    getCompanyListByProductId(productId) {
      return listCompanyByProductId(productId).then(response => {
        this.companyOptions = response.companies.map(item => {
              return {
                value: item.companyId,
                label: item.companyName
              };
            });
        this.form.companyIds = response.companyIds;
      })
    },

    getList() {
      this.loading = true;
      listProduct(this.queryParams).then(response => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.productId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getIndustryTreeselect();
      this.open = true;
      this.title = "添加产品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const productId = row.productId || this.ids
      const productIndustry = this.getProductIndustryTreeselect(productId);
      getProduct(productId).then(response => {
        this.form = response.data;
        this.dynamicTags = response.data.tags;
        this.form.tags = [...this.dynamicTags];
        this.getProductChain(productId, 'upstream');
        this.getProductChain(productId, 'downstream');
        this.getCompanyListByProductId(productId);
        this.$nextTick(() => {
          productIndustry.then(res => {
            let checkedKeys = res.checkedKeys
            checkedKeys.forEach((v) => {
                this.$nextTick(()=>{
                    this.$refs.industry.setChecked(v, true ,false);
                })
            })
          });
        });
        this.open = true;
        this.title = "修改产品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.industryIds = this.getIndustryAllCheckedKeys();
          this.form.tags = [...this.dynamicTags];
          if (this.form.productId != null) {
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    // 公司状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.productName + '"产品吗？').then(function() {
        return changeProductStatus(row.productId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const productIds = row.productId || this.ids;
      this.$modal.confirm('是否确认删除产品编号为"' + productIds + '"的数据项？').then(function() {
        return delProduct(productIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('pms/product/export', {
        ...this.queryParams
      }, `product_${new Date().getTime()}.xlsx`)
    },

    /** 标签 */
    handleClose(tag) {
        this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
        this.form.tags = [...this.dynamicTags];
      },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
        this.form.tags = [...this.dynamicTags];
      }
      this.inputVisible = false;
      this.inputValue = '';
    }
  }
};
</script>
